﻿using ZXing;
using SkiaSharp;
using ZXing.Common;
using ZXing.SkiaSharp.Rendering; 

namespace Agile.Infra.Code;

public class ORCodeService : IORCodeService
{
    /// <summary>
    /// 返回 SKBitmap 图片对象
    /// </summary>
    /// <param name="content"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public SKBitmap GenerateQRCodeAsImage(string content, int width = 300, int height = 300)
    {
        var writer = new BarcodeWriter<SKBitmap>
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new EncodingOptions { Width = width, Height = height },
            Renderer = new SKBitmapRenderer()
        };
        return writer.Write(content);
    }

    /// <summary>
    /// 返回字节数组（PNG格式）
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public byte[] GenerateQRCodeAsBytes(string content)
    {
        using (var bitmap = GenerateQRCodeAsImage(content))
        using (var image = SKImage.FromBitmap(bitmap))
        using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
        {
            return data.ToArray();
        }
    } 
}
